package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.SuperConstants;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class ResourceServiceImpl implements ResourceService {
    private final ResourceMapper resourceMapper;

    /**
     * @param  
     * @return
     */
    @Override
    public List<ResourceVo> resourceList(ResourceDto resourcedto) {
            Resource resource = new Resource();
            BeanUtils.copyProperties(resourcedto, resource);
           List<Resource> list = resourceMapper.selectList(resource);
            return BeanUtil.copyToList(list, ResourceVo.class);
    }
    /**
     * @param resource 
     * @return
     * 树递归
     */
//    @Override
//    public TreeVo resourcetree(ResourceDto resource) {
//        Integer level = resource.getLevel();
//        List<TreeItemVo> list = recursionTree(level, SuperConstants.ROOT_DEPT_PARENT_ID);
//        
//        return TreeVo.builder().items(list).build();
//    }
//   public List<TreeItemVo> recursionTree(Integer level, String parentResourceNo) {
//        //集合TreeItemVo
//        List<TreeItemVo> list = new ArrayList<>();
//        if (level!=0){
//            level--;
//            //拿到根
//            List<Resource> resourceList = resourceMapper.selectList(Resource.builder().parentResourceNo(parentResourceNo).resourceType(SuperConstants.MENU).dataState(SuperConstants.DATA_STATE_0).build());
//            if (CollUtil.isNotEmpty(resourceList)){
//                for (Resource resource : resourceList) {
//                    TreeItemVo treeItem = new TreeItemVo();
//                    treeItem.setId(resource.getResourceNo());   
//                    treeItem.setLabel(resource.getResourceName());
//                    //--level每次减一查找下一层，下一层是resource.getResourceNo()
//                    treeItem.setChildren(recursionTree(level, resource.getResourceNo()));
//                    list.add(treeItem);
//                }
//                
//                
//                
//                
//            }
//            
//            
//            
//        }
//        return list;


        @Override
    public TreeVo resourcetree(ResourceDto resource) {
        Integer level = resource.getLevel();
            List<Resource> resourceList = resourceMapper.selectList(Resource
                    .builder()
                    .resourceType(SuperConstants.MENU)
                    //NoProcessing.processString是方法，拿到所有子孙
                    .dataState(SuperConstants.DATA_STATE_0)
                    //100000000000000转化成了100
                    .resourceNo(NoProcessing.processString(SuperConstants.ROOT_DEPT_PARENT_ID))
                    .build());
        List<TreeItemVo> list = recursionTree2(level,resourceList, SuperConstants.ROOT_DEPT_PARENT_ID);
        return TreeVo.builder().items(list).build();
    }

    private List<TreeItemVo> recursionTree2(Integer level, List<Resource> resourceList, String rootDeptParentId) {
        //集合TreeItemVo
        List<TreeItemVo> list = new ArrayList<>();
        if (level != 0) {
            level--;
            if (CollUtil.isNotEmpty(resourceList)) {
                for (Resource resource : resourceList) {
                    //第一次必须找到根
                    if (StrUtil.equals(resource.getParentResourceNo(),rootDeptParentId)){
                    TreeItemVo treeItem = new TreeItemVo();
                    treeItem.setId(resource.getResourceNo());   
                    treeItem.setLabel(resource.getResourceName());
                    //--level每次减一查找下一层，下一层是resource.getResourceNo()
                    treeItem.setChildren(recursionTree2(level,resourceList, resource.getResourceNo()));
                    list.add(treeItem);
                    }
                }
            }
        }
        return list;
    }

    /**
     * @param resource 
     */
    @Override
    public void Insert(Resource resource) {
        // 检查传入的resource对象是否为空，如果为空则抛出异常
        System.out.println(resource);
        if (BeanUtil.isEmpty(resource)){
            throw new RuntimeException("参数异常");
        }
        // 检查resource对象的parentResourceNo属性的最后三位是否不是"000"，并且长度大于3
        // 如果不符合条件，则抛出BaseException异常，表示菜单深度超出限制
        if (!StrUtil.subSuf(resource.getParentResourceNo(),resource.getParentResourceNo().length()-3).equals("000")&&resource.getParentResourceNo().length()>3){
            throw new BaseException(BasicEnum.MENU_DEPTH_UPPER_LIMIT);
        }
        // 使用NoProcessing工具类生成一个新的resourceNo
        String resourceNo = NoProcessing.createNo(resource.getParentResourceNo(), false);
        Boolean boo = true;
        // 使用一个循环来确保生成的resourceNo是唯一的
        while (boo){
            // 从数据库中查询与parentResourceNo同级的resourceNo
            List<String> resourceNoMysql = resourceMapper.selectresourceNo(resource.getParentResourceNo());
            // 调用resourceNoMysqlandresourceNo方法比较数据库中的resourceNo和新生成的resourceNo是否不相等
            for (String resourcenomysql : resourceNoMysql) {
                if (resourceNoMysqlandresourceNo(resourcenomysql, resourceNo)&& !StrUtil.equals(resourceNoMysql.get(resourceNoMysql.size() - 1), resourcenomysql)){
                    // 如果不相等，说明新生成的resourceNo是唯一的，可以设置到resource对象中并插入数据库
                    resource.setResourceNo(resourceNo);
                    resourceMapper.insert(resource);
                }else {
                    // 如果相等，说明新生成的resourceNo不是唯一的，需要重新生成
                    // 重新生成resourceNo，这次使用递增的方式
                    resourceNo = NoProcessing.createNo(resource.getParentResourceNo(), true);
                    // 再次比较，如果不相等则退出循环
                    boo = !resourceNoMysqlandresourceNo(resourcenomysql,resourceNo);
                }
            }
        }
        // 最后，无论循环是否执行，都会将resource对象插入数据库
        resource.setResourceNo(resourceNo);
        resourceMapper.insert(resource);
    }

    // resourceNoMysqlandresourceNo方法用于比较两个resourceNo是否不相等
    public boolean resourceNoMysqlandresourceNo(String resourceNoMysql,String resourceNo){
        // 如果两个resourceNo不相等，则返回true
        return !StrUtil.equals(resourceNoMysql,resourceNo);
    }

    /**
     * @param resourceDto 
     */
    @Override
    public void updateResource(ResourceDto resourceDto) {
        if (BeanUtil.isEmpty(resourceDto)){
            throw new BaseException(BasicEnum.PARAMS_ERROR);
        }
        resourceMapper.updateResource(resourceDto);
    }


    /**
     * @param resource 
     */
    @Override
    public void dataStateupdate(Resource resource) {
        if (BeanUtil.isEmpty(resource)) {
            throw new BaseException(BasicEnum.PARAMS_ERROR);
        }
        resourceMapper.dataStateupdate(resource);
    }
}
